package com.itheima.reggie.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user,HttpSession session){
        String phone = user.getPhone();

        String code = RandomUtil.randomNumbers(6);

        //SMSUtils2.sendSms(phone,code);//code=387204

//        session.setAttribute(phone,code);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        valueOperations.set("code:"+phone,code,5, TimeUnit.MINUTES);

        System.out.println(code);

        return R.success("验证码发送成功");
    }

    @PostMapping("/login")
    public R loginPhone(@RequestBody Map map,HttpSession session){

        String phone = (String) map.get("phone");

        String code = (String) map.get("code");

        String loginPhone = (String) redisTemplate.opsForValue().get("code:" + phone);

        //String loginPhone = (String) session.getAttribute(phone);

        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){

            return R.error("手机号码或者验证码不能为空");
        }

        if (loginPhone.equals(code)){

            LambdaQueryWrapper<User> qw =new LambdaQueryWrapper<>();

            qw.eq(User::getPhone,phone);

            User one = userService.getOne(qw);

            if (one==null){

                one = new User();

                one.setPhone(phone);

                one.setStatus(1);

                one.setName(phone);

                userService.save(one);

                System.out.println("保存成功");
            }

            session.setAttribute("loginPhone",one);

            redisTemplate.delete("code:"+phone);

            return R.success("登陆成功");
        }

        return R.error("登陆失败");
    }

    @PostMapping("/loginout")
    public R loginoutPhone(HttpSession session){

        session.removeAttribute("loginPhone");

        return R.success(null);
    }




}
